package cn.anecansaitin.whimsy.mixin.common;

import cn.anecansaitin.whimsy.common.effect.IEffectFinishes;
import cn.anecansaitin.whimsy.common.event.ModEventHooks;
import cn.anecansaitin.whimsy.common.register.ModEffects;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;

import java.util.Iterator;

@Mixin(LivingEntity.class)
public abstract class LivingEntityMixin extends Entity {
    public LivingEntityMixin(EntityType<?> pEntityType, Level pLevel) {
        super(pEntityType, pLevel);
    }

    //添加对Effect的拓展支持，当Effect继承了IEffectFinishes接口，则当Effect结束的时候会调用onEffectFinished方法
    @Inject(method = "tickEffects",
            at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;level()Lnet/minecraft/world/level/Level;", ordinal = 0),
            locals = LocalCapture.CAPTURE_FAILHARD)
    public void inject$tickEffects(CallbackInfo ci, Iterator iterator, MobEffect mobeffect) {
        if (!(mobeffect instanceof IEffectFinishes effectFinishes)) {
            return;
        }

        if (effectFinishes.isPlayerClientEffect()) {
            effectFinishes.onEffectFinished((LivingEntity) (Object) this);
        } else if (!level().isClientSide) {
            effectFinishes.onEffectFinished((LivingEntity) (Object) this);
        }
    }

    //发布新事件，当被治疗之后
    @Inject(method = "heal",
            at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;setHealth(F)V", shift = At.Shift.AFTER),
            locals = LocalCapture.CAPTURE_FAILHARD)
    public void inject$heal(float amount, CallbackInfo ci, float health) {
        if (!((Object)this instanceof Player player)) {
            return;
        }

        ModEventHooks.onPlayerHealingCompleted(player, amount, health);
    }
}
